import bpy
from uuid import uuid4
# from ...addon.naming import FluidLabNaming
from ...libs.functions.get_common_vars import get_common_vars
from ...libs.functions.basics import set_active_object, ocultar_post_panel_settings
from .op_list_reuse_base import FLUIDLAB_OT_list_reuse_base
from datetime import datetime


class FLUIDLAB_OT_fluid_interactions_list_add(FLUIDLAB_OT_list_reuse_base):
    bl_idname = "fluidlab.fluid_interactions_list_add"
    bl_label = "Add New Interaction"
    bl_description = "Add Interactions to List"
    bl_options = {"REGISTER", "UNDO"}
    
    def execute(self, context):
        start = datetime.now()

        scn, fluid_groups, fluid_interactions = get_common_vars(context, get_scn=True, get_fluid_groups=True, get_fluid_interactions=True)

        # Obtener todos los grupos de fluidos
        all_groups = fluid_groups.get_all_items
        emitters_obs = set()

        # Obtener todos los emitters interactivos
        for group in all_groups:
            for emitter_item in group.emitters.get_all_items:
                if emitter_item.interactive:
                    emitter_ob = next((ob for ob in emitter_item.group_coll.objects if ob.fluidlab.id_name == "Emitter_" + emitter_item.id_name), None)
                    if emitter_ob and emitter_ob.particle_systems.active:
                        emitters_obs.add(emitter_ob)

        if len(emitters_obs) < 2:
            self.report({'ERROR'}, "It is essential to select at least two collections/emitters!")
            self.restore_indexs(context)
            return {'CANCELLED'}

        # Rebobinar al principio
        scn.frame_set(scn.frame_start)

        # Guardar el objeto activo
        prev_active = context.active_object

        all_interactions = []
        any_included = False

        # Convertir el set en lista:
        emitters_obs = list(emitters_obs)
        # Obtener los sistemas de partículas activos:
        psystems = [ob.particle_systems.active for ob in emitters_obs]
        # Obtener todos los targets existentes:
        existing_targets = [target.name for psys in psystems for target in psys.targets]

        for i, ob in enumerate(emitters_obs):
            psys_active = psystems[i]
            interactued_obs = {ob}

            # Iterar sobre todos los emitters menos el actual
            for rest in emitters_obs:
                if rest == ob:
                    continue

                # Evitar duplicados
                name = f"{rest.name}: {psys_active.name}"
                if name in existing_targets:
                    continue

                # Crear un nuevo target de interacción de fluidos
                with context.temp_override(particle_system=psys_active):
                    bpy.ops.particle.new_target()

                ptarget = psys_active.active_particle_target
                ptarget.object = rest

                any_included = True
                interactued_obs.add(rest)

            all_interactions.append(list(interactued_obs))

        # Agregar las interacciones al listado si hay nuevas
        if any_included:
            id_name = str(uuid4())[:6]
            total = fluid_interactions.length
            padding = len(str(total)) + 1
            label_txt = f"Interaction_{str(total).zfill(padding)}"
            fluid_interactions.add_item(id_name, label_txt, all_interactions)
        else:
            self.report({'WARNING'}, "These interactions have already been included!")

        # Restaurar el objeto activo
        if prev_active:
            set_active_object(context, prev_active)

        # Restaurar los índices previos
        self.restore_indexs(context)

        ocultar_post_panel_settings()

        print("[fluidlab.fluid_interactions_list_add] Time: " + str(datetime.now() - start))
        return {'FINISHED'}

    

    def draw(self, context):

        layout = self.layout
        layout.use_property_decorate = False
        layout.use_property_split = False

        fluid_groups = get_common_vars(context, get_fluid_groups=True)
        active_group = fluid_groups.active

        if active_group:
        
            listados = layout.row(align=True)
            listados.template_list("FLUIDLAB_UL_draw_fluids_groups", "", fluid_groups, "list", fluid_groups, "list_index", rows=3)
        
            fluid_emitters = active_group.emitters
            listados.template_list("FLUIDLAB_UL_draw_fluids_emitters", "", fluid_emitters, "list", fluid_emitters, "list_index", rows=3)